<script setup lang="ts">
import type { FormRules, ElForm } from 'element-plus'
import type { IAccount } from '@/types'

import useLoginStore from '@/store/modules/login'
import { localCache } from '@/utils/cache'

// 1：定义account数据
const account = reactive<IAccount>({
  name: localCache.getCache('name') ?? '',
  password: localCache.getCache('password') ?? ''
})
// 2：定义校验规则
const accountRules: FormRules = {
  name: [
    { required: true, message: '必须输入账号信息', trigger: 'blur' },
    { min: 6, max: 20, message: '长度必须是6~20位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '必须输入账号信息', trigger: 'blur' },
    // { pattern: /^[a-zA-Z0-9]{6,20}$/, message: '长度必须是6~20位', trigger: 'change' }
    { pattern: /^[a-zA-Z0-9]{6,20}$/, message: '长度必须是6~20位', trigger: 'blur' }
  ]
}
// 3：执行账号登录逻辑
const loginStore = useLoginStore()
const formRef = ref<InstanceType<typeof ElForm>>()
const loginAction = (isKeepPassword: boolean) => {
  // 判断校验是否成功，如果校验失败点击登录按钮不发送网络请求
  formRef.value?.validate((valid) => {
    if (valid) {
      // console.log('校验成功')
      const name = account.name
      const password = account.password
      loginStore.loginAccountAction({ name, password }).then(() => {
        // 判断是否需要记住密码
        if (isKeepPassword) {
          localCache.setCache('name', name)
          localCache.setCache('password', password)
        } else {
          localCache.removeCache('name')
          localCache.removeCache('password')
        }
      })
    } else {
      // console.log('校验失败')
      ElMessage.error('Oops, 请输入正确的格式后再操作')
    }
  })
}
// 暴露子组件的方法给父组件调用
defineExpose({
  loginAction
})
</script>

<template>
  <div class="pane-account">
    <el-form :model="account" :rules="accountRules" label-width="60px" size="large" status-icon ref="formRef">
      <!-- 通过prop关联表单校验规则 -->
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" show-password v-model="account.password" />
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="less" scoped></style>
